package myjava.a_string;

/**
 * @Auther: cty
 * @Date: 2019/11/6 下午7:15
 * @Description: 测试可变字符串和不可变字符串序列的陷阱
 * @version: 1.0
 */
public class D_TestTrap {
    public static void main(String[] args) {
        /*使用String进行字符串的拼接*/
        long num1 = Runtime.getRuntime().freeMemory();
        long time1 = System.currentTimeMillis();

        //错误程序！！！
        String str1 = "";
        for(int i=0;i<5000;i++){
            str1 = str1 + i;  //开发中一定不能出现这样的代码，相当于产生了5000个String对象
        }
        System.out.println(str1);

        long num2 = Runtime.getRuntime().freeMemory();
        long time2 = System.currentTimeMillis();
        System.out.println("String占用内存："+(num1-num2));
        System.out.println("String占用时间："+(time2-time1));


        long num3 = Runtime.getRuntime().freeMemory();
        long time3 = System.currentTimeMillis();

        //正确程序!!!
        StringBuilder sb1 = new StringBuilder("");
        for(int i=0;i<5000;i++){
            sb1.append(i);
        }
        System.out.println(sb1);

        long num4 = Runtime.getRuntime().freeMemory();
        long time4 = System.currentTimeMillis();
        System.out.println("StringBuilder占用内存："+(num3-num4));
        System.out.println("StringBuilder占用时间："+(time4-time3));
    }
}
